package com.shqcjd.preinstallglass.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.bridge.OpenEffectBridge;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.AppConstant;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.pojo.LoginBean;
import com.shqcjd.preinstallglass.ui.activity.input.LoginNumberInputActivity;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.PrefUtils;
import com.shqcjd.preinstallglass.util.ToastUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPIOnlySignal;
import io.reactivex.disposables.Disposable;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_login)
    TextView etLogin;
    @BindView(R.id.et_pwd)
    TextView etPwd;
    @BindView(R.id.tv_login)
    Button tvLogin;
    @BindView(R.id.tv_tourist_login)
    Button tv_tourist_login;
    @BindView(R.id.mainUpView1)
    MainUpView mMainUpView;
    @BindView(R.id.main_lay)
    FrameMainLayout main_lay11;

    private Context mContext;
    private AgoraAPIOnlySignal agoraAPIOnlySignal;
    private final int INPUT_FINISH = 25156;
    private int passOrAccount = -1;//0代表账号， 1代表密码

    OpenEffectBridge mOpenEffectBridge;
    View mOldFocus;

    @Override
    protected String getVoiceContent() {
        return "|返回|登录|账号|密码;";
    }

    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果:"+result);
        switch (result) {
            case "返回":
                finish();
                break;
            case "登录":
                tvLogin.performClick();
                break;
            case "账号":
                passOrAccount = 0;
                Intent it = new Intent(mContext, LoginNumberInputActivity.class);
                it.putExtra("str", etLogin.getText().toString().trim());
                startActivityForResult(it, INPUT_FINISH);
                break;
            case "密码":
                passOrAccount = 1;
                Intent its = new Intent(mContext, LoginNumberInputActivity.class);
                its.putExtra("str", etPwd.getText().toString().trim());
                startActivityForResult(its, INPUT_FINISH);
                break;
        }
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        mContext = this;
        agoraAPIOnlySignal = MyApp.the().getmAgoraAPI();
        etPwd.setInputType(InputType.TYPE_NULL);
        etLogin.setInputType(InputType.TYPE_NULL);
        etPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passOrAccount = 1;
                Intent it = new Intent(mContext, LoginNumberInputActivity.class);
                it.putExtra("str", etPwd.getText().toString().trim());
                startActivityForResult(it, INPUT_FINISH);
            }
        });
        etLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passOrAccount = 0;
                Intent it = new Intent(mContext, LoginNumberInputActivity.class);
                it.putExtra("str", etLogin.getText().toString().trim());
                startActivityForResult(it, INPUT_FINISH);
            }
        });

        mMainUpView.setEffectBridge(new EffectNoDrawBridge());
        mOpenEffectBridge = (OpenEffectBridge) mMainUpView.getEffectBridge();
        Drawable testDrawable = null;
        mMainUpView.setUpRectDrawable(testDrawable); // 设置边框图片
        mMainUpView.setUpRectResource(R.drawable.test_rectangle); // 设置边框图片.


        main_lay11.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {

                if (newFocus != null)
//                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                    mMainUpView.setFocusView(newFocus, mOldFocus, 1.0f);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
//                if (newFocus != null) {
//                    testTopDemo(newFocus, scale);
//                }
            }
        });
        etLogin.setNextFocusDownId(R.id.et_pwd);
        etLogin.setNextFocusRightId(R.id.et_pwd);

        etPwd.setNextFocusUpId(R.id.et_login);
        etPwd.setNextFocusLeftId(R.id.et_login);
        etPwd.setNextFocusDownId(R.id.tv_login);
        etPwd.setNextFocusRightId(R.id.tv_login);

        tvLogin.setNextFocusLeftId(R.id.et_pwd);
        tvLogin.setNextFocusRightId(R.id.tv_tourist_login);

        tv_tourist_login.setNextFocusUpId(R.id.tv_login);
        tv_tourist_login.setNextFocusLeftId(R.id.tv_login);
    }


    @OnClick({R.id.tv_login,R.id.tv_tourist_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                login();
                break;
            case R.id.tv_tourist_login:
                touristLogin();
                break;
        }

    }

    private void touristLogin(){
        Map<String, String> map = new HashMap<>();
        map.put("loginName","88888888");
        map.put("password", "123456");
        map.put("application_code", "1");
        ApiService.login(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<LoginBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在登录...");
                    }

                    @Override
                    public void _onNext(ResponseData<LoginBean> retData) {
                        Logger.i("登录"+retData);
                        if (retData != null && retData.retCode == 10000) {
                            PrefUtils.setBoolean(mContext, PrefUtils.FIRST_LOGIN, true);
                            PrefUtils.setInt(mContext, PrefUtils.USER_ID, retData.data.id);
                            PrefUtils.setString(mContext, PrefUtils.USER_CODE, retData.data.user_code);
                            PrefUtils.setString(mContext, PrefUtils.USER_NAME, retData.data.user_name);
                            PrefUtils.setString(mContext, PrefUtils.PHONE_NUMBER, retData.data.phone_number);
                            PrefUtils.setString(mContext, PrefUtils.USER_ICON, retData.data.icon);
                            PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, retData.data.token);
                            PrefUtils.setInt(mContext, PrefUtils.USER_TYPE, retData.data.user_type);

                            //登录信令
                            //登出
                            agoraAPIOnlySignal.logout();
                            //登录声网信令系统
                            agoraAPIOnlySignal.login2(getString(R.string.agora_app_id), retData.data.id + "", "_no_need_token", 0, "", 5, 3);

                            startActivity(new Intent(LoginActivity.this,RouteActivity.class));
                            finish();
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }


                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void login() {
        String phone = etLogin.getText().toString().trim();
        String password = etPwd.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.show(this,"请输入账号", Toast.LENGTH_SHORT);
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtils.show(this,"请输入密码", Toast.LENGTH_SHORT);
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("loginName",phone);
        map.put("password", password);
        map.put("application_code", "1");
        ApiService.login(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<LoginBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在登录...");
                    }

                    @Override
                    public void _onNext(ResponseData<LoginBean> retData) {
                        Logger.i("登录"+retData);
                        if (retData != null && retData.retCode == 10000) {
                            PrefUtils.setBoolean(mContext, PrefUtils.FIRST_LOGIN, true);
                            PrefUtils.setInt(mContext, PrefUtils.USER_ID, retData.data.id);
                            PrefUtils.setString(mContext, PrefUtils.USER_CODE, retData.data.user_code);
                            PrefUtils.setString(mContext, PrefUtils.USER_NAME, retData.data.user_name);
                            PrefUtils.setString(mContext, PrefUtils.PHONE_NUMBER, retData.data.phone_number);
                            PrefUtils.setString(mContext, PrefUtils.USER_ICON, retData.data.icon);
                            PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, retData.data.token);
                            PrefUtils.setInt(mContext, PrefUtils.USER_TYPE, retData.data.user_type);

                            //登录信令
                            //登出
                            agoraAPIOnlySignal.logout();
                            //登录声网信令系统
                            agoraAPIOnlySignal.login2(getString(R.string.agora_app_id), retData.data.id + "", "_no_need_token", 0, "", 5, 3);

                            startActivity(new Intent(LoginActivity.this,RouteActivity.class));
                            finish();
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }


                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == INPUT_FINISH && RESULT_OK == resultCode){
            String s = data.getStringExtra("input_key");
            if(passOrAccount==0){
                etLogin.setText(s);
            }else{
                etPwd.setText(s);
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
